<?php

namespace App\Repositories\Eloquent\Biz;

use Illuminate\Container\Container as App;
use App\Repositories\Eloquent\Repository;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use App\Repositories\Eloquent\Mgt\UserRepository as User;
use App\Repositories\Eloquent\Biz\TrackRepository as Track;
use App\Repositories\Eloquent\Biz\RecordRepository as Record;
use App\Repositories\Eloquent\Biz\SummaryRepository as Summary;

class WeixinRepository extends Repository
{

    protected $user, $record, $track, $summary;

    protected $debug;

    protected $columns;
    /**
     * @param App
     */
    public function __construct(App $app, User $user, Track $track, Record $record, Summary $summary)
    {
        parent::__construct($app);

        $this->user = $user;

        $this->track = $track;

        $this->record = $record;

        $this->summary = $summary;

        //短信调试开关
        $this->debug = env('SMS_DEBUG');

    }

    /**
     * 指定模型名称
     *
     * @return mixed
     */
    function model()
    {
        return 'App\Models\Mgt\User';
    }


    /**
     * [用户登录]
     * @param  [type] $request [description]
     * @return [type]          [description]
     */
    public function login($request)
    {
        if(!$this->debug){
            if($request->smscode != \Session::get('smscode'))
                return $this->responseFail(405, '验证码不正确');
        }


        if ( \Auth::guard()->attempt([
            'mobile' => $request->mobile,
            'password' => DEFAULT_PASSWORD,
            //'type'=$request->type
            ])) {
            return $this->responseSuccess('登录成功', $request, route('wx.index'));
        }

        return $this->responseFail(500, '登录失败');
    }


    /**
     * [活动报名](已作废)
     * @param  [type] $request [description]
     * @return [type]          [description]
     */
    public function apply($request)
    {
        $user = $this->user->show($request->uid);

        if( strcmp($user->mobile, $request->mobile) != 0 )
            return $this->responseFail(405, '手机号码不一致');

        if ( $user->applied($request->aid, $user->type) )
            return $this->responseFail(406, '活动已报名');

        if( !!$user->setTrack($request->aid, $user->type, true) )
            return $this->responseSuccess('报名成功', $user, route('wx.mySign'));

        return $this->responseFail(500, '报名失败');
    }

    /**
     * [培训报名]
     * @param  [type] $request [description]
     * @return [type]          [description]
     */
    public function enrol($request, $type)
    {

        $user = $this->user->show($request->uid);

        if( strcmp($user->mobile, $request->mobile) != 0 )
            return $this->responseFail(405, '手机号码不一致');

        if(!$this->debug){
            if($request->smscode != Session::get('smscode'))
                return $this->responseFail(405, '验证码不正确');
        }

        if(empty($request->grade_id))
            return $this->responseFail(404, '请选择需要报名的课程');

        $publish = \App\Models\Edu\Publish::find($request->publish_id);

        if( strtotime(now()) <= $publish->begin || strtotime(now()) >= $publish->end){
            return $this->responseFail(405, '不在报名时间内');
        }



        $grade = \App\Models\Edu\Grade::find($request->grade_id);
        if( $grade->limited == 1 && count($grade->accepted)>=$grade->number)
            return $this->responseFail(406, '名额已满');

        if ( $user->grade($request->publish_id, $request->grade_id) )
            return $this->responseFail(406, '重复报名');

        if( !!$user->setEnrol($request, $grade) )
            return $this->responseSuccess('报名成功', $user, route('wx.myPublish',$this->user->transformType($type)));

        return $this->responseFail(500, '报名失败');
    }

    /**
     * [用户注册]
     * @param  [type] $request [description]
     * @return [type]          [description]
     */
    public function register($request)
    {
        if(!$this->debug){
            if($request->smscode != \Session::get('smscode'))
                return $this->responseFail(405, '验证码不正确');
        }

        $birthday = date('Ymd',strtotime($request->birthday) );

        /*if( !$this->model::checkAge($birthday) )
            return $this->responseFail(405, '年龄超限');*/

        if( $this->model::checkIdcard( $request->idcard, $request->type ) )
            return $this->responseFail(405, '身份证号码已注册');

        if( $this->model::checkMobile( $request->mobile, $request->type ) )
            return $this->responseFail(405, '手机号码已注册');

        \DB::beginTransaction();
        try{
            $user = $this->create([
                'name'      => $request->name,
                'account'   => \App\Models\Mgt\Util::generate( $this->model->max('account') ),
                'password'  => \Hash::make(DEFAULT_PASSWORD),
                'mobile'    => $request->mobile,
                'idcard'    => $request->idcard,
                'gender'    => $request->gendar,
                'birthday'  => date('Y-m-d',strtotime( $request->birthday)),
                'school_id' => is_null($request->school) ? 1:$request->school,
                'branch_id' => 1,
                'created_at' => time(),
                'type'      => $request->type,
                'source'    => $request->source,
            ]);
            if ($result = !!$user) {
                $user->summary()->create([
                    'type'          =>$user->type,
                    'updated_at'    =>time()
                ]);

                //2020.4.23增加注册送积分
                /*$activity = \App\Models\Mgt\Activity::nonCheck();

                $this->track->set($user, $activity, \App\Models\Biz\Track::TRACK_TYPE_EXTRA);

                //签到时，积分值默认为用户类型，阅读者1，志愿者2
                $point = $this->record->set($user, $activity, 5, \App\Models\Biz\Track::TRACK_TYPE_EXTRA);

                $this->summary->set($user, 3, $point); */

                \Auth::guard()->login($user);
            }

            \DB::commit();

            return $this->responseSuccess('账号注册成功', $user, route('wx.index'));

        } catch (Exception $e) {

            \DB::rollback();

            return $this->responseFail(500,'账号注册失败');
        }

    }


    /**
     * 资料更新
     * @param  [type] $request [description]
     * @return [type]          [description]
     */
    public function renew($request)
    {
        $user = $this->find($request->uid);

        $birthday = date('Ymd',strtotime($request->birthday) );

        if( $this->model::checkIdcard( $request->idcard, $request->type ) )
            return $this->responseFail(405, '身份证号码已注册');

        if( $this->model::checkMobile( $request->mobile, $request->type ) )
            return $this->responseFail(405, '手机号码已注册');

        \DB::beginTransaction();
        try{
            $this->update([
                'name'      => $request->name,
                'idcard'    => $request->idcard,
                'gender'    => $request->gendar,
                'birthday'  => date('Y-m-d',strtotime( $request->birthday)),
            ],$user->id);

            \DB::commit();

            return $this->responseSuccess('资料更新成功', $user, route('wx.index'));

        } catch (Exception $e) {

            \DB::rollback();

            return $this->responseFail(500,'资料更新失败');
        }

    }

}